import { CtlBase } from './CtlBase'
import { parseYvanPropChangeVJson } from './CtlUtils'
import { YvEvent, YvEventDispatch } from './YvanEvent'
import webix from 'webix'

export class CtlUploader extends CtlBase<CtlUploader> {

  onAfterFileAdd?: YvEvent<CtlUploader, any>
  onBeforeFileAdd?: YvEvent<CtlUploader, any>
  onBindRequest?: YvEvent<CtlUploader, any>
  onEnter?: YvEvent<CtlUploader, any>
  onUploadComplete?: YvEvent<CtlUploader, any>
  onFileUpload?: YvEvent<CtlUploader, any>
  onFileUploadError?: YvEvent<CtlUploader, any>

  static create(module: any, vjson: any): CtlUploader {
    const that = new CtlUploader(vjson)
    that._module = module

    const yvanProp = parseYvanPropChangeVJson(vjson, [
        'onAfterFileAdd',
        'onBeforeFileAdd',
        'onBindRequest',
        'onEnter',
        'onFileUpload',
        'onFileUploadError',
        'onUploadComplete'
    ])

    // 将 vjson 存至 _webix (此时 _webix 还只是 vjson 代理对象)
    that._webixConfig = vjson

    // 将 yvanProp 合并至当前 Ctl 对象
    _.assign(that, yvanProp)

    _.merge(vjson, that._webixConfig, {
      on: {
        onInited() {
          that.attachHandle(this, { ...vjson, ...yvanProp })
        },
        onDestruct: function () {
          that.removeHandle()
        },
        onAfterFileAdd: function(file: any) {
          YvEventDispatch(that.onAfterFileAdd, that, file)
        },
        onBeforeFileAdd: function(file: any) {
          YvEventDispatch(that.onBeforeFileAdd, that, file)
        },
        onBindRequest: function() {
          YvEventDispatch(that.onBindRequest, that, undefined)
        },
        onEnter: function(ev: any){
          YvEventDispatch(that.onEnter, that, ev)
        },
        onFileUpload: function (file: any, response: any) {
          YvEventDispatch(that.onFileUpload, that, file)
        },
        onFileUploadError: function (file: any, response: any) {
          YvEventDispatch(that.onFileUploadError, that, file)
        },
        onUploadComplete: function(response: any){
          YvEventDispatch(that.onUploadComplete, that, response)
        }
      }
    })
    return that
  }
}
